﻿using System.Text;
using System.Text.Json;

namespace Framework.EncryptionService
{
    /// <summary>
    /// 数据类型转换拓展
    /// </summary>
    internal static partial class ExtensionsHelper
    {
        private static readonly Lazy<JsonSerializerOptions> jsonSerializer = new Lazy<JsonSerializerOptions>(() => new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
        /// <summary>
        /// 将string类型反序列化至指定对象
        /// </summary>
        /// <typeparam name="T">返回值对象类型</typeparam>
        /// <param name="json">待反序列化字符串</param>
        /// <returns></returns>
        // 定义一个扩展方法 ConvertToObject，用于将 JSON 字符串转换为指定类型的对象
        public static T ConvertToObject<T>(this string json)
        {
            // 调用 JsonSerializer.Deserialize 方法进行反序列化，并传入配置选项
            return JsonSerializer.Deserialize<T>(json, jsonSerializer.Value);
        }

        /// <summary>
        /// 将string类型反序列化至指定对象列表
        /// </summary>
        /// <typeparam name="T">返回值对象类型</typeparam>
        /// <param name="json">待反序列化字符串</param>
        /// <returns></returns>
        public static List<T> ConvertToObjects<T>(this string json) => JsonSerializer.Deserialize<List<T>>(json);

        /// <summary>
        /// 将object对象序列化为json字符串
        /// </summary>
        /// <typeparam name="T">待序列化对象类型</typeparam>
        /// <param name="obj">待序列化对象</param>
        /// <returns></returns>
        public static string ConvertToString<T>(this T obj) where T : class, new()
        {
            return JsonSerializer.Serialize(obj);
        }

        /// <summary>
        /// 将object对象序列化为json字符串
        /// </summary>
        /// <typeparam name="T">待序列化对象类型</typeparam>
        /// <param name="obj">待序列化对象</param>
        /// <returns></returns>
        public static string ConvertToString(this object obj)
        {
            return JsonSerializer.Serialize(obj);
        }

        #region -- bite转换

        /// <summary>
        /// 将string转换为byte数组
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] ConvertToBytes(this string str) => Encoding.UTF8.GetBytes(str);

        /// <summary>
        /// 将byte数组转换为string
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ConvertToString(this byte[] byt) => Encoding.UTF8.GetString(byt);

        /// <summary>
        /// 将bast64转换为byte数组
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] FromBase64String(this string str) => Convert.FromBase64String(str);

        /// <summary>
        /// 将byte数组转换为bast64
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToBase64String(this byte[] byt) => Convert.ToBase64String(byt);
        #endregion
    }
}
